var express = require('express');

var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var zookeeper = require('node-zookeeper-client');
var fs = require("fs");

var app = express();
var client = zookeeper.createClient('localhost:2181');
var database = path.join(__dirname, 'database');

app.engine('html', require('ejs').renderFile);
// 定义EJS模板引擎和模板文件位置，也可以使用jade或其他模型引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
// app.set('views', __dirname );
// 定义icon图标
app.use(favicon(__dirname + '/public/favicon.ico'));
// 定义日志和输出级别
app.use(logger('dev'));
// 定义数据解析器
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 定义cookie解析器
app.use(cookieParser());
// 定义静态文件目录
app.use(express.static(path.join(__dirname, 'public')));



// 404错误处理
// app.use(function(req, res, next) {
//   var err = new Error('Not Found');
//   err.status = 404;
//   next(err);
// });
// 开发环境，500错误处理和错误堆栈跟踪
// if (app.get('env') === 'development') {
//   app.use(function(err, req, res, next) {
//     res.status(err.status || 500);
//     res.render('error', {
//       message: err.message,
//       error: err
//     });
//   });
// }
// 生产环境，500错误处理
// app.use(function(err, req, res, next) {
//   res.status(err.status || 500);
//   res.render('error', {
//     message: err.message,
//     error: {}
//   });
// });




client.on('state', function (state) {
    if (state === zookeeper.State.SYNC_CONNECTED) {
        console.log('Client state is changed to connected.');
    }
});
function listChildren(client, path) {
    client.getChildren(
        path,
        function (event) {
            console.log('Got watcher event: %s', event);
            listChildren(client, path);
        },
        function (error, children, stat) {
            if (error) {
                console.log(
                    'Failed to list children of %s due to: %s.',
                    path,
                    error
                );
                return;
            }

            console.log('Children of %s are: %j.', path, children);
        }
    );
}

client.once('connected', function () {
    console.log('Connected to ZooKeeper.');
    listChildren(client, "/");
});

client.connect();



app.get('/', function(req, res){
  // res.send('hello world');
  res.render("index");
});


app.get("/charts.html",function(req,res){
  res.render("charts");
});
app.get("/email1.html",function(req,res){
  res.render("email1");
});
app.get("/email2.html",function(req,res){
  res.render("email2");
});
app.get("/email3.html",function(req,res){
  res.render("email3");
});
app.get("/email4.html",function(req,res){
  res.render("email4");
});
app.get("/email5.html",function(req,res){
  res.render("email5");
});
app.get("/email6.html",function(req,res){
  res.render("email6");
});
app.get("/extra_404_option1.html",function(req,res){
  res.render("extra_404_option1");
});
app.get("/extra_404_option2.html",function(req,res){
  res.render("extra_404_option2");
});
app.get("/extra_404_option3.html",function(req,res){
  res.render("extra_404_option3");
});
app.get("/extra_500_option1.html",function(req,res){
  res.render("extra_500_option1");
});
app.get("/extra_500_option2.html",function(req,res){
  res.render("extra_500_option2");
});
app.get("/extra_faq.html",function(req,res){
  res.render("extra_faq");
});
app.get("/extra_image_manager.html",function(req,res){
  res.render("extra_image_manager");
});
app.get("/extra_invoice.html",function(req,res){
  res.render("extra_invoice");
});
app.get("/extra_lock.html",function(req,res){
  res.render("extra_lock");
});
app.get("/extra_pricing_table.html",function(req,res){
  res.render("extra_pricing_table");
});
app.get("/extra_profile.html",function(req,res){
  res.render("extra_profile");
});
app.get("/extra_search.html",function(req,res){
  res.render("extra_search");
});
app.get("/form_component.html",function(req,res){
  res.render("form_component");
});
app.get("/form_dropzone.html",function(req,res){
  res.render("form_dropzone");
});
app.get("/form_fileupload.html",function(req,res){
  res.render("form_fileupload");
});
app.get("/form_layout.html",function(req,res){
  res.render("form_layout");
});
app.get("/form_samples.html",function(req,res){
  res.render("form_samples");
});
app.get("/form_validation.html",function(req,res){
  res.render("form_validation");
});
app.get("/form_wizard.html",function(req,res){
  res.render("form_wizard");
});
app.get("/inbox.html",function(req,res){
  res.render("inbox");
});
app.get("/inbox_inbox.html",function(req,res){
  res.render("inbox_inbox");
});
app.get("/index.html",function(req,res){
  res.render("index");
});
app.get("/layout_ajax.html",function(req,res){
  res.render("layout_ajax");
});
app.get("/layout_ajax_content_2.html",function(req,res){
  res.render("layout_ajax_content_2");
});
app.get("/layout_ajax_content_3.html",function(req,res){
  res.render("layout_ajax_content_3");
});
app.get("/layout_blank_page.html",function(req,res){
  res.render("layout_blank_page");
});
app.get("/layout_boxed_not_responsive.html",function(req,res){
  res.render("layout_boxed_not_responsive");
});
app.get("/layout_boxed_page.html",function(req,res){
  res.render("layout_boxed_page");
});
app.get("/layout_email.html",function(req,res){
  res.render("layout_email");
});
app.get("/layout_horizontal_menu1.html",function(req,res){
  res.render("layout_horizontal_menu1");
});
app.get("/layout_horizontal_menu2.html",function(req,res){
  res.render("layout_horizontal_menu2");
});
app.get("/layout_horizontal_sidebar_menu.html",function(req,res){
  res.render("layout_horizontal_sidebar_menu");
});
app.get("/layout_promo.html",function(req,res){
  res.render("layout_promo");
});
app.get("/layout_sidebar_closed.html",function(req,res){
  res.render("layout_sidebar_closed");
});
app.get("/login.html",function(req,res){
  res.render("login");
});
app.get("/login_soft.html",function(req,res){
  res.render("login_soft");
});
app.get("/maps_google.html",function(req,res){
  res.render("maps_google");
});
app.get("/maps_vector.html",function(req,res){
  res.render("maps_vector");
});
app.get("/page_about.html",function(req,res){
  res.render("page_about");
});
app.get("/page_blog.html",function(req,res){
  res.render("page_blog");
});
app.get("/page_blog_item.html",function(req,res){
  res.render("page_blog_item");
});
app.get("/page_calendar.html",function(req,res){
  res.render("page_calendar");
});
app.get("/page_coming_soon.html",function(req,res){
  res.render("page_coming_soon");
});
app.get("/page_contact.html",function(req,res){
  res.render("page_contact");
});
app.get("/page_news.html",function(req,res){
  res.render("page_news");
});
app.get("/page_news_item.html",function(req,res){
  res.render("page_news_item");
});
app.get("/page_timeline.html",function(req,res){
  res.render("page_timeline");
});
app.get("/portlet_draggable.html",function(req,res){
  res.render("portlet_draggable");
});
app.get("/portlet_general.html",function(req,res){
  res.render("portlet_general");
});
app.get("/table_advanced.html",function(req,res){
  res.render("table_advanced");
});
app.get("/table_basic.html",function(req,res){
  res.render("table_basic");
});
app.get("/table_editable.html",function(req,res){
  res.render("table_editable");
});
app.get("/table_managed.html",function(req,res){
  res.render("table_managed");
});
app.get("/table_responsive.html",function(req,res){
  res.render("table_responsive");
});
app.get("/ui_buttons.html",function(req,res){
  res.render("ui_buttons");
});
app.get("/ui_general.html",function(req,res){
  res.render("ui_general");
});
app.get("/ui_jqueryui.html",function(req,res){
  res.render("ui_jqueryui");
});
app.get("/ui_modals.html",function(req,res){
  res.render("ui_modals");
});
app.get("/ui_nestable.html",function(req,res){
  res.render("ui_nestable");
});
app.get("/ui_sliders.html",function(req,res){
  res.render("ui_sliders");
});
app.get("/ui_tabs_accordions.html",function(req,res){
  res.render("ui_tabs_accordions");
});
app.get("/ui_tiles.html",function(req,res){
  res.render("ui_tiles");
});
app.get("/ui_tree.html",function(req,res){
  res.render("ui_tree");
});
app.get("/ui_typography.html",function(req,res){
  res.render("ui_typography");
});



fs.exists(database, function (exists) {
  console.log(exists ? "database exists" : "database not exists!");
  if(!exists){
  	fs.mkdir(database,0777,function(err){
  		console.error(err);
  	});
  }else{
  	var config = JSON.stringify([{name:"a",host:"127.0.0.1",port:2181},{name:"b",host:"127.0.0.1",port:2182}]);
  	fs.writeFile(database + '/config.json', config, function (err) {
	  if (err) throw err;
	  console.log('It\'s saved!'); //文件被保存
	  console.log("config : %j ", JSON.parse(fs.readFileSync(database + '/config.json')));
	});	
  }
});
fs.watchFile(database + '/config.json', function (curr, prev) {
  console.log('the current mtime is: ' + curr.mtime);
  console.log('the previous mtime was: ' + prev.mtime);
});
fs.watch(database + '/config.json', function (event, filename) {
  console.log('event is: ' + event);
  if (filename) {
    console.log('filename provided: ' + filename);
  } else {
    console.log('filename not provided');
  }
});
app.post("/zookeeper-directory",function(req,res){
    var data = [];
     data[0]={"name":"shihui","id":"/shihui","path":"/shihui","isParent":"true"};
     data[1]={"name":"shihui/name","id":"/name","path":"/shihui/name","isParent":"false"};     
     res.json(data);
});
app.listen(3000);